package com.cl.service;

import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.database.ContentObserver;
import android.net.Uri;
import android.os.Handler;
import android.os.IBinder;
import android.telephony.PhoneStateListener;
import android.telephony.SmsMessage;
import android.telephony.TelephonyManager;
import android.util.Log;

import com.android.internal.telephony.ITelephony;
import com.cl.db.dao.BlackNumberDao;

import java.lang.reflect.Method;

//import com.android.internal.telephony.ITelephony;
public class CallSmsSafeService extends Service {
	private static String TAG = "CallSmsSafeService";
	private TelephonyManager tm;
	private BlackNumberDao dao;
	private InnerSMSReceiver receiver;
	private MyPhoneStateListener listener;

	@Override
	public IBinder onBind(Intent arg0) {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public void onCreate() {
		// TODO Auto-generated method stub
		super.onCreate();
		listener = new MyPhoneStateListener();
		dao = new BlackNumberDao(getApplicationContext());
		
		// 监听来电
		tm = (TelephonyManager) getSystemService(TELEPHONY_SERVICE);
		tm.listen(listener, PhoneStateListener.LISTEN_CALL_STATE);
		// 注册一个去电广播接收者
		receiver = new InnerSMSReceiver();
		IntentFilter filter = new IntentFilter();
		filter.addAction("android.provider.Telephony.SMS_RECEIVED");
		filter.setPriority(1000);
		registerReceiver(receiver, filter);
	}

	@Override
	public void onDestroy() {
		// TODO Auto-generated method stub
		super.onDestroy();
		// 用代码取消注册广播接收者
		unregisterReceiver(receiver);
		receiver = null;
		tm.listen(listener, PhoneStateListener.LISTEN_NONE);
	}

	class InnerSMSReceiver extends BroadcastReceiver {

		@Override
		public void onReceive(Context context, Intent intent) {
			Object[] objs = (Object[]) intent.getExtras().get("pdus");
			// 一个obj对应一条短信
			for (Object obj : objs) {
				SmsMessage sms = SmsMessage.createFromPdu((byte[]) obj);
				String phone = sms.getOriginatingAddress();
				if (dao.find(phone)) {
					String result = dao.findMode(phone);
					if ("2".equals(result) || "3".equals(result)) {
						Log.i(TAG, "拦截短信");
						abortBroadcast();
					}
				}
				// 演示代码。
				String body = sms.getMessageBody();
				if (body.contains("fapiao")) {
					// 你的头发票亮的很 语言分词技术。
					Log.i(TAG, "拦截发票短信");
					abortBroadcast();
				}
			}
		}
	}

	private class MyPhoneStateListener extends PhoneStateListener {
		@Override
		public void onCallStateChanged(int state, String incomingNumber) {
			// TODO Auto-generated method stub
			super.onCallStateChanged(state, incomingNumber);
			switch (state) {
			case TelephonyManager.CALL_STATE_RINGING:
				String result = dao.findMode(incomingNumber);
				if ("1".equals(result) || "3".equals(result)) {
					Log.i(TAG, "挂断电话。。。。");
				   //监听数据库变化，删除呼叫记录
					ContentResolver resolver = getContentResolver();
					Uri uri = Uri.parse("content://call_log/calls");
					resolver.registerContentObserver(uri, true, new CallLogObserver(incomingNumber, new Handler()));
					endcall();
				}
				break;

			}
		}

	}
	/**
	 * 监听呼叫记录
	 * @author Administrator
	 *
	 */
	class CallLogObserver extends ContentObserver {
		private String incomingNumber;
		public CallLogObserver(String incomingNumber,Handler handler) {
			super(handler);
			this.incomingNumber = incomingNumber;
		}

		@Override
		public void onChange(boolean selfChange) {
			// TODO Auto-generated method stub
			super.onChange(selfChange);
			deleteCallLog(incomingNumber);
			getContentResolver().unregisterContentObserver(this);
		}
		
	}
	
	/**
	 * 删除呼叫记录
	 * @param incomingNumber
	 */
	public void deleteCallLog(String incomingNumber) {
		ContentResolver resolver = getContentResolver();
		Uri uri = Uri.parse("content://call_log/calls");
		System.out.println("删除 "+incomingNumber);
		resolver.delete(uri, "number = ?", new String[]{incomingNumber});
		
	}
	
	/**
	 * 挂断电话
	 */
	public void endcall() {
		try {
			Class<?> clazz = CallSmsSafeService.class.getClassLoader().loadClass("android.os.ServiceManager");
			Method method = clazz.getDeclaredMethod("getService",String.class);
			IBinder b = (IBinder) method.invoke(null,TELEPHONY_SERVICE);
			//获取到了原生未经修改包装的系统电话的管理服务
			ITelephony iTelephony = ITelephony.Stub.asInterface(b);
			iTelephony.endCall();//挂断电话
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
}
